<template>
    <el-select-v2 
        ref="selectMultiRef"
        class="bar"
        v-model="modelValue[itemValue]"
        filterable
        placeholder="Select"
        clearable
        highlight-current-row
        :options="filteredOptionsMethod(options).value"
        @change="props.updateOptions($refs)"
        :filter-method="filterMethod"
        multiple
        >
    </el-select-v2>
</template>

<script lang="ts" setup name="MultiSelect">
    import { computed, onBeforeMount, onMounted, ref, watch } from 'vue';

    let selectMultiRef:any = ref()  
    let options:any = ref([])
    let initAllOptions: any = ref([])
    const itemValue = ref('') // 选项名

    const props = defineProps(['selectedValues', 'searchItem', 'filterMethod', 'updateOptions', 'filteredOptions', 'modelValue'])

    const filterMethod = (query:any) => {
        if (query) {
            const escapeStringRegexp = (string = '') => string.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d')
            const regexp = new RegExp(escapeStringRegexp(query), 'i')
            let filteredOptions = initAllOptions.value.filter((opt: any) => {
                return query ? regexp.test(opt.label || '') : true
            }).sort((a: any, b: any) => {
                const aStartsWith = a.label.toLowerCase().startsWith(query.toLowerCase());
                const bStartsWith = b.label.toLowerCase().startsWith(query.toLowerCase());
                return (aStartsWith === bStartsWith) ? (a.label.length < b.label.length ? -1 : 1) : (aStartsWith ? -1 : 1);
            })

            options.value = filteredOptionsMethod(filteredOptions).value
        } else {
            options.value = filteredOptionsMethod(initAllOptions.value).value
        }
    };

    const filteredOptionsMethod = (opts: any) => {
        // 直接返回的是Object类型的数据，用的时候加上.value
        return computed(() => {
            const options = Array.isArray(opts) ? opts : [];
            return options.filter((option: any) => !props.modelValue[props.searchItem.value]?.includes(option.value));
        });
    };
    
    defineExpose({selectMultiRef})

    watch(props.searchItem, (newValue:any) => {
        // 此处的newValue就是整个searchItem的Object，不需要再加value。如果再加上value，则是value的字符串
        initAllOptions.value = props.filteredOptions(newValue).value
        options.value = props.filteredOptions(newValue).value
    }, {deep: true})

    onMounted(() => {
        itemValue.value = props.searchItem.value
    })

</script>